/* 网络请求工具类 */

var isProduct = process.env.NODE_ENV === 'production';
var isDevelop = process.env.NODE_ENV === 'development';

function getToken() {
	let token = '1';
	return token;
}
/* 请求头 */
var _header = {
	// 'content-type': 'application/x-www-form-urlencoded',
	// 'version': '1.0.0',
	'token': uni.getStorageSync('userinfo').token || ''

}

//处理发送的数据，对数据加密
function handleSendData(params) {
	if (isDevelop) {
		// console.log("===== httpUtils 请求参数 =====", params);
	}
	return params;
}

//处理返回数据，对数据解密
function handleReturnData(res) {
	if (isDevelop) {
		// console.log("===== httpUtils 返回数据 =====", res);
	}
	return res;
}

/**
 * function: 显示/隐藏加载框
 * @isShow 显示/隐藏
 * @loadingText 加载框文字
 */
function showLoading(isShow, loadingText) {
	if (isShow == false) {
		uni.hideLoading()
		return
	}
	if (loadingText == undefined) {} else {
		if (loadingText != "" && isShow == true) {
			uni.showLoading({
				title: loadingText,
			})
		}
	}
}

/* 进行请求 */
const request = (url, method, params, loadingText) => {
	showLoading(true, loadingText)
	let token = getApp().globalData.loginTempToken
	_header = {
		'Cache-Control': 'max-age=60', //60秒
		'token': token ? token : ''
		// 'Content-Type': 'application/x-www-form-urlencoded'
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: url,
			method: method,
			data: handleSendData(params),
			header: _header,
			success(res) {
				console.log("------> " + JSON.stringify(res));
				if (res.data.code == 10002) {
					getApp().globalData.loginTempToken = '';
					uni.reLaunch({
						url: '/pages/login/login'
					})
				}
				resolve(handleReturnData(res.data))
				setTimeout(() => {

					showLoading(false)
				}, 1000)
			},
			fail(error) {

				console.log(error)
				reject(error)
			},
			complete() {}
		})
	});
}

/* get请求 */
function get(url, params, loadingText) {
	console.log(params);
	return request(url, "GET", params, loadingText);
}

/* post请求 */
function post(url, params, loadingText) {
	params.token = getApp().globalData.loginTempToken;
	params.marshalling_id = getApp().globalData.marshalling_id;
	params.company_id = getApp().globalData.company_id;
	params.cabinet_id = getApp().globalData.cabinet_id;
	params.version = getApp().globalData.version;
	console.log("请求地址： " + url);
	console.log("请求参数： " + JSON.stringify(params));
	return request(url, "POST", params, loadingText);
}

/* 文件上传 */
const uploadFile = (url, filePath, params, loadingText) => {
	// console.log("-----文件上传------");

	console.log(params);

	showLoading(true, loadingText)
	_header = {
		'Auth-Token': uni.getStorageSync('token'),
		'Content-Type': 'multipart/form-data'
	}
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: url,
			filePath: filePath,
			name: 'filename',
			method: "POST",
			formData: params,
			header: _header,
			success(res) {
				console.log(res.data);
				resolve(handleReturnData(JSON.parse(res.data)))
			},
			fail(error) {
				reject(error)
			},
			complete: info => {
				showLoading(false)
			}
		})
	})
}

/* 图片加载 */
const loadImage = (url, params) => {
	// console.log("-----图片下载------");
	let auth = '_auth=' + getToken()
	if (url.indexOf("?") > 0) {
		url = url + "&" + auth
	} else {
		url = url + "?" + auth
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: url,
			method: 'GET',
			data: params,
			header: _header,
			responseType: 'arraybuffer',
			success(res) {
				if (res.statusCode == 200 && res.data.byteLength) {
					let base64 = wx.arrayBufferToBase64(res.data);
					let img = 'data:image/jpeg;base64,' + base64
					resolve(img)
				} else {
					resolve(null)
				}
			},
			fail(error) {
				reject(error)
			},
			complete: info => {}
		})
	})
}

/* 通过module.exports方式提供给外部调用 */
module.exports = {
	request,
	uploadFile,
	loadImage,
	get: get,
	post: post,
}

/* 
使用方法 ：

1.在要使用的js文件导入
var HTTP = require('../../../../http/httpUtils.js');

2. 调用
HTTP.post('url', params).then(res => {
}).catch(error=>{
});

 */